<template>
  <van-popup
    v-model="show"
    position="bottom"
    close-on-click-overlay
    @click-overlay="clexts"
    style="width: 100%;height: 100%;background-color: #f3f3f3;">
    <div class="control-search">
      <div class="nav-control-search">
        <div class="inner">
          <i class="close-control-search" @click="clext"></i>
          <div class="input-control-search">
            <form class="search-form" action="/" @submit.prevent="handleOnSubmit">
              <div class="input-box">
                <span class="search-type show-search-type-box" @click.stop="showSearchType = !showSearchType">{{ searchType }}</span>
                <i class="arrow-down show-search-type-box" @click.stop="showSearchType = !showSearchType"></i>
                <transition name="fade">
                  <div v-if="showSearchType" class="search-type-box">
                    <ul>
                      <li class="item" @click="searchType = '商品'"><i class="icon-search-type type-goods"></i>商品</li>
                      <li class="item" @click="searchType = '店铺'"><i class="icon-search-type type-store"></i>店铺</li>
                    </ul>
                  </div>
                </transition>
                <input type="search" v-model="keyword" class="search-input" maxlength="200" placeholder="搜索商品/店铺" autofocus="autofocus">
                <i class="search-icon"></i>
                <input type="submit" class="search-submit">
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <div v-if="searchType === '商品' &&  autoCompleteData.length" class="auto-complete">
      <ul>
        <li v-for="(word, index) in autoCompleteData" :key="index" @click="handleOnSubmit1(word.words)">
          <span>{{ word.words }}</span>
          <span>约{{ word.goods_num }}个商品</span>
        </li>
      </ul>
    </div>
    <template v-else>
      <div class="hot-keyword-search">
        <div class="title-hot-keyword">
          <span>大家都在搜</span>
        </div>
        <div class="content-hot-keyword">
          <ul class="key-words">
            <li
              v-for="keyword in hot_keywords"
              :key="keyword.id"
              class="item"
              @click="handleOnSubmit(keyword.hot_name)"
            >{{ keyword.hot_name }}</li>
          </ul>
        </div>
      </div>
      <div class="history-search">
        <template v-if="searchHistory && searchHistory.length">
          <ul>
            <li v-for="(his, index) in searchHistory" :key="his" class="his-item">
              <span @click="handleOnSubmits(his)">{{ his }}</span>
              <i @click="handleDeleteHistory(index)" class="icon-close"></i>
            </li>
          </ul>
          <van-button size="small" class="clear-his-btn" @click="handleClearHistory">清空搜索历史</van-button>
        </template>
        <div v-else style="width: 100%;text-align: center;line-height: 100px">暂无搜索记录...</div>
      </div>
    </template>
  </van-popup>
</template>

<script>
  import * as API_Home from '@/api/home'
  import * as API_Goods from '@/api/goods'
  import Storage from '@/utils/storage'

  export default {
    name: 'Search',
    props: ['show'],
    data() {
      return {
        keyword: this.$route.query.keyword || '',
        hot_keywords: [],
        // 显示搜索类型
        showSearchType: false,
        // 搜索类型
        searchType: '商品',
        // 搜索历史
        searchHistory: [],
        // 自动补全数据
        autoCompleteData: '',
        // 自动补全字符串
        autoCompleteStr: '',
        searchHistory1:''
      }
    },
    watch: {
      keyword: 'handleSearchChange'
    },
    mounted() {
      /** 获取热门关键词 */
      API_Home.getHotKeywords().then(response => this.hot_keywords = response)
      this.$nextTick(() => {
        document.querySelector('body').addEventListener('click', this.handleCloseSearcyType);
      })
      // 初始化搜索历史
      const searchHistory = Storage.getItem('search_history')
      if(searchHistory) this.searchHistory = JSON.parse(searchHistory)
    },
    methods: {
      clext(){
        this.keyword = ''
        this.$emit('close')
      },
      clexts(){
        this.$emit('close')
      },
      clextst(){
        this.showSearchType = false
      },
      handleOnSubmits(his){
        this.keyword = his
      },
      handleOnSubmit1(){
        this.handleOnSubmit()
      },
      /** 隐藏搜索类型盒子 */
      handleCloseSearcyType() {
        this.showSearchType = false
      },
      /** 提交表单之拦截 */
      handleOnSubmit(_keyword) {
        this.$emit('close')
        let { searchType, keyword } = this
        if (typeof _keyword === 'string') keyword = _keyword
        const searchHistory = JSON.parse(JSON.stringify(this.searchHistory))
        this.searchHistory1 = searchHistory
        const _index = searchHistory.indexOf(keyword)
        if (_index !== -1) {
          searchHistory.splice(_index, 1)
        } else if (searchHistory.length > 9) {
          searchHistory.pop()
        }
        if (keyword.trim()) searchHistory.splice(0, 0, keyword)
        this.$set(this, 'searchHistory', searchHistory)
        Storage.setItem('search_history', JSON.stringify(searchHistory))
        if (searchType === '商品') {
          this.$router.push({path:'/goods',query:{keyword:keyword}}).catch(error => error);
        } else {
          this.$router.push({path:'/shop',query:{keyword:keyword}}).catch(error => error);
        }
      },
      /** 删除搜索历史 */
      handleDeleteHistory(index) {
        this.searchHistory.splice(index, 1)
        Storage.setItem('search_history', JSON.stringify(this.searchHistory))
      },
      /** 清空搜索历史 */
      handleClearHistory() {
        this.$confirm('确定要清空搜索历史吗？', () => {
          this.$set(this, 'searchHistory', [])
          Storage.removeItem('search_history')
        })
      },
      /** 搜索关键字发生改变 */
      handleSearchChange() {
        let _str = this.keyword
        if (this.searchType !== '商品') return
        if (!_str) {
          this.autoCompleteData = []
          return
        }
        _str = _str.trim()
        API_Goods.getKeywordNum(_str).then(response => {
          this.autoCompleteData = response
        })
      }
    },
    destroyed () {
      document.removeEventListener('click', this.handleCloseSearcyType)
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  .control-search {
    width: 100%;
  }
  .nav-control-search {
    width: 100%;
    height: 45px;
    background-color: #f3f3f3;
  }
  .control-search .nav-control-search:after {
    content: '';
    position: absolute;
    top: 45px;
    width: 100%;
    height: 1px;
    background-color: #ccc;
  }
  .control-search .nav-control-search .inner {
    display: flex;
    align-items: center;
    width: 100%;
    height: 100%;
  }
  .control-search .close-control-search {
    display: block;
    width: 10.66vw;
    height: 100%;
    background: url('') no-repeat center;
    background-size: 60%;
  }
  .control-search .input-control-search {
    position: relative;
    width: 89.34vw;
    height: 100%;
  }
  .control-search .input-box {
    display: flex;
    position: relative;
    width: 98%;
    height: 66%;
    border: 1px solid #bfbfbf;
    border-radius: 3px;
    margin-top: 1.8%;
    background-color: #fff;
  }
  .control-search .search-type {
    position: relative;
    width: 10%;
    min-width: 30px;
    background-color: #f3f3f3;
    text-align: right;
    font-size: 14px;
    line-height: 33px;
    overflow: hidden;
  }
  .control-search .arrow-down {
    position: relative;
    display: block;
    width: 3%;
    height: 33px;
    background: #f3f3f3 url('') no-repeat center;
    background-size: 8px;
    border-right: 1px solid #bfbfbf;
    padding: 0 2px;
  }
  .search-input {
    border: none;
    outline: none;
    background-color: #fff;
    width: 87%;
    padding-left: 2%;
    height: 33px;
    font-size: 16px;
    tap-highlight-color:rgba(0,0,0,0);
    -webkit-tap-highlight-color:rgba(0,0,0,0);
  }
  .search-icon, .search-submit {
    position: absolute;
    right: 0;
    top: 0;
    width: 11%;
    height: 100%;
  }
  .search-icon {
    background: #f3f3f3 url('') no-repeat center;
    background-size: 50%;
    display: block;
    z-index: 102;
    border-left: 1px solid #bfbfbf;
  }
  .search-submit {
    z-index: 103;
    opacity: 0;
    outline: none;
    border: 0;
  }
  .search-type-box {
    position: absolute;
    left: 0;
    top: 33px;
    z-index: 101;
    padding: 10px;
    -webkit-transition: all .3s ease-out;
    transition: all .3s ease-out;
  }
  .search-type-box ul {
    background: #484d50;
    border-radius: 6px;
    width: 140px;
    overflow: hidden;
    color: #c7c8c9;
    &:after {
      position: absolute;
      left: 20px;
      top: 5px;
      content: '';
      display: inline-block;
      width: 10px;
      height: 10px;
      background: #484d50;
      -webkit-transform: rotate(45deg);
    }
  }
  .search-type-box li {
    border-top: 1px solid #707476;
    margin-top: -1px;
    height: 35px;
    line-height: 35px;
  }

  .icon-search-type {
    float: left;
    position: relative;
    width: 40px;
    height: 35px;
    &.type-goods {
      background: url('') no-repeat center;
      background-size: 50%;
    }
    &.type-store {
      background: url('') no-repeat center;
      background-size: 50%;
    }
  }
  .title-hot-keyword {
    width: 100%;
    line-height: 25px;
    background-color: #eee;
    text-align: left;
    span {
      line-height: 25px;
      font-size: 12px;
      color: #999;
      margin-left: 6%;
    }
  }
  .content-hot-keyword {
    background-color: #fff;
    padding-top: 10px;
  }
  .key-words {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .key-words .item {
    width: 30%;
    border: 1px solid #e0e0e0;
    text-align: center;
    line-height: 30px;
    font-size: 12px;
    color: #848689;
    border-radius: 15px;
    margin-bottom: 10px;
    margin-left: 2%;
    overflow: hidden;
  }
  .fade-enter-active, .fade-leave-active {
    transition: all .3s ease;
  }
  .fade-enter, .fade-leave-to {
    transform: translateY(10px);
    opacity: 0;
  }
  .history-search {
    width: 100%;
    margin-top: 10px;
    background-color: #fff;
    overflow: hidden;
    .his-item {
      padding: 10px;
      overflow: hidden;
    }
    span {
      float: left;
      display: inline-block;
      text-align: left;
      width: calc(100% - 50px);
    }
    .icon-close {
      position: relative;
      top: 2px;
      display: inline-block;
      float: right;
      width: 50px;
      height: 14px;
      background: url("") no-repeat right;
      background-size: 14px;
    }
    .clear-his-btn {
      display: block;
      margin: 10px auto;
    }
  }
  .auto-complete {
    height: calc(100% - 50px);
    background-color: #FFFFFF;
    padding: 0 10px;
    li {
      display: flex;
      justify-content: space-between;
      line-height: 30px;
      color: #333;
    }
  }
</style>
